import React, { useState, useEffect } from 'react';
import {
  Container,
  Grid,
  Card,
  CardContent,
  CardMedia,
  Typography,
  Button,
  Box,
  Tabs,
  Tab,
  Paper,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Snackbar,
  Alert,
  CircularProgress,
  Divider,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow
} from '@mui/material';
import { Link, useLocation } from 'react-router-dom';
import Navbar from '../components/Navbar';
import { getAvailableProducts, purchaseProduct, getUserOrders } from '../api/store';
import { getBalance } from '../api/profile';

import { navigationItems } from '../App';


// 商品默认图片
const productImages = {
  'VIP': 'https://img.icons8.com/color/96/000000/vip.png',
  'GIFT': 'https://img.icons8.com/color/96/000000/gift.png',
  'OTHER': 'https://img.icons8.com/color/96/000000/box.png'
};

function Store() {
  const location = useLocation();
  
  // 状态变量
  const [products, setProducts] = useState([]);
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [tabValue, setTabValue] = useState(0);
  const [userBalance, setUserBalance] = useState(0);
  const [user, setUser] = useState(null);
  const [confirmDialog, setConfirmDialog] = useState({
    open: false,
    product: null
  });
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: '',
    severity: 'success'
  });
  
  // 获取用户信息
  useEffect(() => {
    // 从 localStorage 获取用户信息
    const userToken = localStorage.getItem('token');
    if (userToken) {
      try {
        const userInfo = JSON.parse(localStorage.getItem('user'));
        setUser(userInfo);
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    }
  }, []);
  
  // 加载商品和用户余额
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        // 并行请求数据
        const [productsRes, balanceRes, ordersRes] = await Promise.all([
          getAvailableProducts(),
          getBalance(),
          getUserOrders()
        ]);
        
        if (productsRes && productsRes.data) {
          setProducts(productsRes.data);
        }
        
        if (balanceRes && balanceRes.data) {
          setUserBalance(balanceRes.data.balance || 0);
        }
        
        if (ordersRes && ordersRes.data) {
          setOrders(ordersRes.data);
        }
      } catch (error) {
        console.error('获取数据失败:', error);
        setSnackbar({
          open: true,
          message: '获取数据失败: ' + (error.message || '服务器错误'),
          severity: 'error'
        });
      } finally {
        setLoading(false);
      }
    };
    
    fetchData();
  }, []);
  
  // 处理标签切换
  const handleTabChange = (event, newValue) => {
    setTabValue(newValue);
  };
  
  // 打开确认购买对话框
  const handleBuyClick = (product) => {
    setConfirmDialog({
      open: true,
      product
    });
  };
  
  // 关闭确认购买对话框
  const handleCloseDialog = () => {
    setConfirmDialog({
      open: false,
      product: null
    });
  };
  
  // 确认购买
  const handleConfirmPurchase = async () => {
    if (!confirmDialog.product) return;
    
    try {
      const res = await purchaseProduct(confirmDialog.product.id);
      
      if (res && res.data && res.data.success) {
        // 更新用户余额
        setUserBalance(res.data.remainingPoints || 0);
        
        // 重新加载订单
        const ordersRes = await getUserOrders();
        if (ordersRes && ordersRes.data) {
          setOrders(ordersRes.data);
        }
        
        setSnackbar({
          open: true,
          message: `成功购买 ${confirmDialog.product.name}！`,
          severity: 'success'
        });
        
        // 切换到订单标签
        setTabValue(1);
      } else {
        throw new Error(res.data?.message || '购买失败');
      }
    } catch (error) {
      console.error('购买失败:', error);
      setSnackbar({
        open: true,
        message: '购买失败: ' + (error.message || '服务器错误'),
        severity: 'error'
      });
    } finally {
      handleCloseDialog();
    }
  };
  
  // 关闭提示信息
  const handleCloseSnackbar = () => {
    setSnackbar({ ...snackbar, open: false });
  };
  
  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString();
  };
  
  // 获取商品图片
  const getProductImage = (product) => {
    return productImages[product.type] || productImages.OTHER;
  };

  return (
    <div className="App" style={{ backgroundColor: '#fefaff', minHeight: '100vh' }}>
      <Navbar />
      <Container
        maxWidth="false"
        sx={{
          backdropFilter: 'blur(4px)',
          backgroundColor: 'rgba(255,255,255,0.6)',
          borderRadius: 3,
          p: 2,
          mt: 3,
        }}
      >
        <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
          <Tabs
            value={location.pathname}
            indicatorColor="secondary"
            textColor="secondary"
            variant="scrollable"
            scrollButtons="auto"
            sx={{
              borderBottom: '2px solid #f3e5f5',
              mb: 2,
              '& .MuiTab-root': {
                transition: 'all 0.3s ease-in-out',
              },
              '& .Mui-selected': {
                color: '#8e24aa',
                fontWeight: 'bold',
              },
              '& .MuiTabs-indicator': {
                height: 3,
                backgroundColor: '#ce93d8',
                borderRadius: 2,
              }
            }}
          >
            {navigationItems
              .filter(item => !item.adminOnly || (user && user.role === 'admin'))
              .map((item) => (
              <Tab
                key={item.path}
                label={item.label}
                value={item.path}
                component={Link}
                to={item.path}
                sx={{
                  minWidth: 100,
                  borderRadius: 2,
                  mx: 0.5,
                  transition: 'all 0.3s',
                  color: '#8e24aa',
                  '&:hover': {
                    backgroundColor: '#ffe0f0',
                    color: '#d81b60',
                  },
                  '&.Mui-selected': {
                    fontWeight: 'bold',
                    color: '#d81b60',
                    backgroundColor: '#fff0f5',
                  },
                }}
              />
            ))}
          </Tabs>
        </Box>
      </Container>
      
      <Container maxWidth="false" sx={{ paddingTop: 3 }}>
        <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
          <Paper elevation={3} sx={{ 
            p: 3, 
            mb: 4,
            borderRadius: 3,
            background: 'linear-gradient(135deg, #fff0f5 0%, #fce4ec 100%)',
            boxShadow: '0 4px 20px rgba(200, 100, 255, 0.1)',
          }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
              <Typography variant="h5" component="h1" sx={{ color: '#8e24aa', fontWeight: 'bold' }}>VIP商店</Typography>
              <Typography variant="h6" sx={{ color: '#d81b60' }}>
                当前积分: <span style={{ fontWeight: 'bold' }}>{userBalance}</span>
              </Typography>
            </Box>
            
            <Box sx={{ borderBottom: 1, borderColor: '#f3e5f5', mb: 3 }}>
              <Tabs 
                value={tabValue} 
                onChange={handleTabChange}
                indicatorColor="secondary"
                textColor="secondary"
                sx={{
                  '& .MuiTab-root': {
                    transition: 'all 0.3s ease-in-out',
                    color: '#8e24aa',
                  },
                  '& .Mui-selected': {
                    color: '#d81b60',
                    fontWeight: 'bold',
                  },
                  '& .MuiTabs-indicator': {
                    backgroundColor: '#ce93d8',
                    height: 3,
                    borderRadius: 2,
                  }
                }}
              >
                <Tab label="商品列表" />
                <Tab label="我的订单" />
              </Tabs>
            </Box>
            
            {loading ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', p: 5 }}>
                <CircularProgress />
              </Box>
            ) : (
              <>
                {/* 商品列表标签页 */}
                {tabValue === 0 && (
                  <Grid container spacing={3}>
                    {products.length === 0 ? (
                      <Box sx={{ width: '100%', textAlign: 'center', p: 5 }}>
                        <Typography color="text.secondary">暂无可用商品</Typography>
                      </Box>
                    ) : (
                      products.map((product) => (
                        <Grid item xs={12} sm={6} md={4} key={product.id}>
                          <Card sx={{ 
                            height: '100%', 
                            display: 'flex', 
                            flexDirection: 'column',
                            borderRadius: 3,
                            transition: 'transform 0.3s',
                            boxShadow: '0 4px 15px rgba(200, 100, 255, 0.1)',
                            '&:hover': {
                              transform: 'translateY(-8px)',
                              boxShadow: '0 12px 25px rgba(200, 100, 255, 0.2)',
                            }
                          }}>
                            <CardMedia
                              component="img"
                              sx={{ height: 140, objectFit: 'contain', pt: 2, backgroundColor: '#fef6ff' }}
                              image={getProductImage(product)}
                              alt={product.name}
                            />
                            <CardContent sx={{ flexGrow: 1, backgroundColor: '#fff9fc' }}>
                              <Typography gutterBottom variant="h5" component="div" sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
                                {product.name}
                              </Typography>
                              <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                                {product.description}
                              </Typography>
                              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <Typography variant="h6" sx={{ color: '#d81b60', fontWeight: 'bold' }}>
                                  {product.price} 积分
                                </Typography>
                                {product.type === 'VIP' && (
                                  <Typography variant="body2" sx={{ color: '#9e9e9e' }}>
                                    有效期: {product.duration} 天
                                  </Typography>
                                )}
                              </Box>
                            </CardContent>
                            <Box sx={{ p: 2, pt: 0, backgroundColor: '#fff9fc' }}>
                              <Button 
                                variant="contained" 
                                fullWidth
                                onClick={() => handleBuyClick(product)}
                                disabled={userBalance < product.price}
                                sx={{
                                  borderRadius: 2,
                                  background: 'linear-gradient(45deg, #8e24aa 30%, #d81b60 90%)',
                                  color: 'white',
                                  fontWeight: 'bold',
                                  '&:hover': {
                                    background: 'linear-gradient(45deg, #6a1b9a 30%, #c2185b 90%)',
                                  },
                                  '&.Mui-disabled': {
                                    background: '#e0e0e0',
                                    color: '#9e9e9e'
                                  }
                                }}
                              >
                                {userBalance < product.price ? '积分不足' : '购买'}
                              </Button>
                            </Box>
                          </Card>
                        </Grid>
                      ))
                    )}
                  </Grid>
                )}
                
                {/* 订单列表标签页 */}
                {tabValue === 1 && (
                  <TableContainer component={Paper} sx={{ 
                    maxHeight: 440,
                    borderRadius: 3,
                    boxShadow: '0 4px 15px rgba(200, 100, 255, 0.1)',
                    overflow: 'hidden'
                  }}>
                    <Table stickyHeader>
                      <TableHead>
                        <TableRow sx={{ 
                          '& th': { 
                            backgroundColor: '#f8bbd0',
                            color: '#8e24aa',
                            fontWeight: 'bold'
                          } 
                        }}>
                          <TableCell>订单ID</TableCell>
                          <TableCell>商品ID</TableCell>
                          <TableCell>价格</TableCell>
                          <TableCell>状态</TableCell>
                          <TableCell>创建时间</TableCell>
                          <TableCell>更新时间</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {orders.length === 0 ? (
                          <TableRow>
                            <TableCell colSpan={6} align="center" sx={{ color: '#9e9e9e' }}>暂无订单</TableCell>
                          </TableRow>
                        ) : (
                          orders.map((order) => (
                            <TableRow key={order.id} sx={{ 
                              '&:nth-of-type(odd)': { backgroundColor: '#fff9fc' },
                              '&:hover': { backgroundColor: '#fce4ec' },
                              transition: 'background-color 0.3s'
                            }}>
                              <TableCell>{order.id}</TableCell>
                              <TableCell>{order.productId}</TableCell>
                              <TableCell sx={{ color: '#d81b60', fontWeight: 'bold' }}>{order.price}</TableCell>
                              <TableCell sx={{ 
                                color: order.status === 'COMPLETED' ? '#4caf50' : 
                                       order.status === 'PENDING' ? '#ff9800' : '#f44336',
                                fontWeight: 'bold'
                              }}>{order.status}</TableCell>
                              <TableCell>{formatDate(order.createdAt)}</TableCell>
                              <TableCell>{formatDate(order.updatedAt)}</TableCell>
                            </TableRow>
                          ))
                        )}
                      </TableBody>
                    </Table>
                  </TableContainer>
                )}
              </>
            )}
          </Paper>
          
          <Paper elevation={3} sx={{ 
            p: 3,
            borderRadius: 3,
            background: 'linear-gradient(135deg, #e0f7fa 0%, #e6f7ff 100%)',
            boxShadow: '0 4px 20px rgba(100, 100, 255, 0.1)',
          }}>
            <Typography variant="h6" gutterBottom sx={{ color: '#8e24aa', fontWeight: 'bold' }}>VIP会员特权</Typography>
            <Box sx={{ mt: 2 }}>
              <Grid container spacing={2}>
                <Grid item xs={12} md={4}>
                  <Box sx={{ 
                    p: 2, 
                    border: '1px solid #f3e5f5', 
                    borderRadius: 2,
                    transition: 'transform 0.3s',
                    '&:hover': {
                      transform: 'translateY(-5px)',
                      boxShadow: '0 10px 20px rgba(200, 100, 255, 0.15)'
                    }
                  }}>
                    <Typography variant="subtitle1" gutterBottom sx={{ fontWeight: 'bold', color: '#d81b60' }}>
                      高级搜索功能
                    </Typography>
                    <Typography variant="body2" sx={{ color: '#9e9e9e' }}>
                      使用高级搜索功能，更精准地找到您需要的资源。
                    </Typography>
                  </Box>
                </Grid>
                <Grid item xs={12} md={4}>
                  <Box sx={{ 
                    p: 2, 
                    border: '1px solid #f3e5f5', 
                    borderRadius: 2,
                    transition: 'transform 0.3s',
                    '&:hover': {
                      transform: 'translateY(-5px)',
                      boxShadow: '0 10px 20px rgba(200, 100, 255, 0.15)'
                    }
                  }}>
                    <Typography variant="subtitle1" gutterBottom sx={{ fontWeight: 'bold', color: '#d81b60' }}>
                      更高的下载速度
                    </Typography>
                    <Typography variant="body2" sx={{ color: '#9e9e9e' }}>
                      享受更高的下载速度限制，快速获取您喜爱的内容。
                    </Typography>
                  </Box>
                </Grid>
                <Grid item xs={12} md={4}>
                  <Box sx={{ 
                    p: 2, 
                    border: '1px solid #f3e5f5', 
                    borderRadius: 2,
                    transition: 'transform 0.3s',
                    '&:hover': {
                      transform: 'translateY(-5px)',
                      boxShadow: '0 10px 20px rgba(200, 100, 255, 0.15)'
                    }
                  }}>
                    <Typography variant="subtitle1" gutterBottom sx={{ fontWeight: 'bold', color: '#d81b60' }}>
                      专属客户支持
                    </Typography>
                    <Typography variant="body2" sx={{ color: '#9e9e9e' }}>
                      获得专属客户支持，解决您在使用过程中遇到的问题。
                    </Typography>
                  </Box>
                </Grid>
              </Grid>
            </Box>
          </Paper>
        </Box>
      </Container>
      
      {/* 确认购买对话框 */}
      <Dialog 
        open={confirmDialog.open} 
        onClose={handleCloseDialog}
        PaperProps={{
          sx: {
            borderRadius: 3,
            boxShadow: '0 10px 30px rgba(200, 100, 255, 0.2)',
            overflow: 'hidden'
          }
        }}
      >
        <DialogTitle sx={{ 
          backgroundColor: '#f8bbd0', 
          color: '#8e24aa',
          fontWeight: 'bold'
        }}>确认购买</DialogTitle>
        <DialogContent sx={{ mt: 2 }}>
          {confirmDialog.product && (
            <>
              <Typography variant="h6" gutterBottom sx={{ color: '#8e24aa', fontWeight: 'bold' }}>{confirmDialog.product.name}</Typography>
              <Typography variant="body1" paragraph sx={{ color: '#757575' }}>{confirmDialog.product.description}</Typography>
              <Divider sx={{ my: 2, borderColor: '#f3e5f5' }} />
              <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                <Typography sx={{ color: '#9e9e9e' }}>价格:</Typography>
                <Typography fontWeight="bold" sx={{ color: '#d81b60' }}>{confirmDialog.product.price} 积分</Typography>
              </Box>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                <Typography sx={{ color: '#9e9e9e' }}>当前积分:</Typography>
                <Typography fontWeight="bold" sx={{ color: '#8e24aa' }}>{userBalance}</Typography>
              </Box>
              <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                <Typography sx={{ color: '#9e9e9e' }}>购买后剩余:</Typography>
                <Typography fontWeight="bold" sx={{ 
                  color: userBalance - (confirmDialog.product?.price || 0) < 0 ? '#f44336' : '#4caf50'
                }}>{userBalance - (confirmDialog.product?.price || 0)}</Typography>
              </Box>
            </>
          )}
        </DialogContent>
        <DialogActions sx={{ p: 2, backgroundColor: '#fafafa' }}>
          <Button 
            onClick={handleCloseDialog}
            sx={{ 
              color: '#9e9e9e',
              '&:hover': { backgroundColor: '#f5f5f5' }
            }}
          >
            取消
          </Button>
          <Button 
            onClick={handleConfirmPurchase} 
            variant="contained" 
            sx={{
              borderRadius: 2,
              background: 'linear-gradient(45deg, #8e24aa 30%, #d81b60 90%)',
              color: 'white',
              fontWeight: 'bold',
              '&:hover': {
                background: 'linear-gradient(45deg, #6a1b9a 30%, #c2185b 90%)',
              }
            }}
          >
            确认购买
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* 提示信息 */}
      <Snackbar 
        open={snackbar.open} 
        autoHideDuration={6000} 
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
        sx={{ 
          '& .MuiAlert-root': {
            borderRadius: 3,
            boxShadow: '0 4px 20px rgba(200, 100, 255, 0.2)',
          }
        }}
      >
        <Alert 
          onClose={handleCloseSnackbar} 
          severity={snackbar.severity} 
          sx={{ 
            width: '100%',
            ...(snackbar.severity === 'success' && {
              backgroundColor: '#f8bbd0',
              color: '#8e24aa',
              '& .MuiAlert-icon': { color: '#d81b60' }
            }),
            ...(snackbar.severity === 'error' && {
              backgroundColor: '#ffebee',
              color: '#c62828',
              '& .MuiAlert-icon': { color: '#d32f2f' }
            })
          }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </div>
  );
}

export default Store; 